dataKey = 'thispagekey'
#这个地址作为开始踩流量的标记
@.startUrl = "#{chrome.extension.getURL('popup.html')}#start"

#得到关键词一行的html
getTrHtml = (name='',cnt=10)->
	"""
		<tr>
		<td>
		<input name="keywordName[]" type="text" value="#{name}" placeholder="请输入宝贝搜索关键词"></td>
		<td>
		<input name="keywordCnt[]" type="number" class="span1" value="#{cnt}" size="10" maxlength="10" placeholder="请输入宝贝搜索关键词的次数" min="1" max="150"></td>
		</tr>
	"""

#保存界面数据
@.saveUserData = ->
	obj = {}
	obj[dataKey] = $('form').serializeObject()
	chrome.storage.local.set obj

#展示界面数据
showUserData = (callback)->
	chrome.storage.local.get(dataKey,(item)->
		obj =
			sellername:''
			password:''
			keywordName:['']
			keywordCnt:[10]
		advSetting =
			maxSearchPage:4
			speed:-10
			mainViewTimeMin:3
			mainViewTimeMax:5
			otherViewTimeMin:2
			otherViewTimeMax:4
			probability:[80,30,10,0]
		if item and item[dataKey]
			obj = item[dataKey]
		obj = $.extend advSetting,obj
		tbody = ''
		if obj.keywordName
			for v,i in obj.keywordName
				tbody += getTrHtml v,obj.keywordCnt[i] if v
		unless tbody
			tbody += getTrHtml()
		tpl = """
			<form class="form-horizontal" style="padding:5px">
				  <table width="200" border="1" class="table table-bordered">
				  <thead>
					<tr>
						<td colspan="2">
							<label>店主旺旺用户名:
								<input name="sellername" value="#{obj.sellername}" type="text" id="sellername" required="required" placeholder="输入店主旺旺用户名" title"请输入店主的旺旺用户名" />
								<button id="taobao" type="submit"  class="btn btn-primary">开始踩流量</button>
							</label>
							<label id="pwLabel">
								服务验证码：<input id="password" name="password" value="#{obj.password}" placeholder="请输入服务验证码" title="服务验证码是您购买服务的时候，卖家分配给你的" type="text" />
							</label>
							<button id="addLine" type="button" class="btn">增加关键词</button>
				<button id="save" type="button" class="btn">保存</button>
				<a href="login.html" class="btn hide">小号登录</a>
				<a href="buy.html" class="btn order" target="_blank">刷单</a>
				<button class="btn showAdv" type="button">高级设置</a>
						</td>
					</tr>
					<tr>
					  <td>宝贝搜索关键词</td>
					  <td>搜索次数</td>
					</tr>
				  </thead>
				  <tbody id="keywordtbody">
				  	#{tbody}
				  </tbody>
				  <tfoot>
				  	<tr><td colspan="2" id="popad"></td></tr>
				  </tfoot>
				</table>



				<div id="advSetting">
					<div class="control-group">
						<label class="control-label" for="maxSearchPage">搜索页数</label>
						<div class="controls">
							<div class="input-append">
								<input class="span1" type="number" id="maxSearchPage" name="maxSearchPage" required="required" value="#{obj.maxSearchPage}" min="1" /><span class="add-on">页</span>
							</div>
						</div>
					</div>
					<div class="control-group">
						<label class="control-label" for="speed">浏览宝贝滚动速度</label>
						<div class="controls">
								慢<input type="range" id="speed" name="speed" required="required" value="#{obj.speed}" min="-20" max="0" class="span2" />快
						</div>
					</div>
					<div class="control-group">
						<label class="control-label" for="mainViewTimeMin">主宝贝浏览时间</label>
						<div class="controls">
							<div class="input-append">
								<input class="span1" type="number" id="mainViewTimeMin" name="mainViewTimeMin" required="required" value="#{obj.mainViewTimeMin}" min="1" /><span class="add-on">分钟</span>
							</div>
							到
							<div class="input-append">
								<input class="span1" type="number" id="mainViewTimeMax" name="mainViewTimeMax" value="#{obj.mainViewTimeMax}" min="2" required="required" /><span class="add-on">分钟</span>
							</div>
						</div>
					</div>
					<div class="control-group">
						<label for="otherViewTimeMin" class="control-label">其它宝贝浏览时间</label>
						<div class="controls">
							<div class="input-append">
								<input class="span1" type="number" id="otherViewTimeMin" name="otherViewTimeMin" required="required" value="#{obj.otherViewTimeMin}" min="1" /><span class="add-on">分钟</span>
							</div>
							到
							<div class="input-append">
								<input class="span1" type="number" id="otherViewTimeMax" name="otherViewTimeMax" value="#{obj.otherViewTimeMax}" min="2" required="required" /><span class="add-on">分钟</span>
							</div>
						</div>
					</div>
					<div class="control-group">
						<label class="control-label">浏览第2到第5个宝贝的概率</label>
						<div class="controls">
							<div class="input-append">
								<input type="number" class="span1" name="probability[]" required="required" value="#{obj.probability[0]}" min="0" max="100" title="浏览第二个宝贝的概率" /><span class="add-on">%</span>
							</div>
							<div class="input-append">
								<input type="number" class="span1" name="probability[]" required="required" value="#{obj.probability[1]}" min="0" max="100" title="浏览第三个宝贝的概率" /><span class="add-on">%</span>
							</div>
							<div class="input-append">
								<input type="number" class="span1" name="probability[]" required="required" value="#{obj.probability[2]}" min="0" max="100" title="浏览第四个宝贝的概率" /><span class="add-on">%</span>
							</div>
							<div class="input-append">
								<input type="number" class="span1" name="probability[]" required="required" value="#{obj.probability[3]}" min="0" max="100" title="浏览第五个宝贝的概率" /><span class="add-on">%</span>
							</div>
						</div>
					</div>
				</div>
			  </form>
					
		"""
		$('body').html(tpl)
		callback()
	)


#界面展示完成
showUserData(->
	###
	# 绑定事件
	###
	#增加关键词
	$('#addLine').click(->
		$('#keywordtbody').append $(getTrHtml())
		$('[name="keywordName[]"]:last').focus()
	)
	#保存数据
	$('#save').click saveUserData
	#关闭页面
	#window.onbeforeunload=noProxy
	#检查关键词是否填写
	$('form').submit ->
		has = off
		nameNot =
			'?':'店主旺旺名中不允许有“?”'
			'？':'店主旺旺名中不允许有“？”'
			' ':'店主旺旺名中不请允许有空格'
		sellnameval = $('#sellername').val()
		if sellnameval.length <3
			alert '店主旺旺名至少3个字'
			$('#sellername').focus()
			return false
		for char,msg of nameNot
			if sellnameval.indexOf(char)>-1
				alert(msg)
				return off

		keyInput = $('[name="keywordName[]"]').each ->
			if this.value
				has = on
				off
		if has
			saveUserData()
			setTimeout(->
				if startUrl == location.href
					location.reload()
				else
					open startUrl
			,1000)
		else
			alert '请输入宝贝关键词'
			keyInput.focus()
		off
	#自动去旺旺名的空白
	$('#sellername').blur ->
		this.value = this.value.trim()
	if location.href == startUrl
		gotaobao() #直接开始踩
		setInterval(checkTabs ,1000)
	else if '#init'==location.hash
		#启动软件先删除缓存
		delCook on
	$('.showAdv').click ->
		$('#advSetting').show()
	#得到自己权限
	$.getJSON "#{serverUrlPre}Index/getMyProperty&#{new Date().getTime()}",$('form').serialize(),(property)->
		if property&2
			$('.order').show()
		if property&4
			$('.showAdv').show()
	showPercent()
	#显示广告信息
	$.getJSON "#{serverUrlPre}Ad/popad",sellername:$('[name="sellername"]').val(),(data)->
		$('#popad').html(data.msg)
)

#################后台数据
#关闭其它tabs
@.closeOthers = ->
	chrome.tabs.getAllInWindow (tabs)->
		#console.log tabs
		finded = 0
		for tab in tabs
			#console.log tab.url.indexOf 'chrome-extension://'
			if tab.url==startUrl and !finded
				finded = 1
				continue
			chrome.tabs.remove tab.id

#tabs的状态检查
reLoadTabTimes = {}
@.checkTabs = ->
	chrome.tabs.getAllInWindow (tabs)->
		for tab in tabs
			tabUrl = tab.url
			#不在允许域名之外的都说明出错，直接删除缓存重新开始
			currentDomain = tabUrl.split(/\//g)[2]
			if startUrl!=tabUrl and currentDomain not in ['www.taobao.com','s.taobao.com','item.taobao.com','detail.tmall.com']
				delCook on
				reloadPage -2
				break
			if tabUrl.indexOf('taobao.com')>0 and tab.status == 'complete'
				#console.log tab
				if tab.title.indexOf(tab.url) > -1 or tab.url.indexOf(tab.title) > -1
					#页面没有打开
					if tab.url.indexOf('s.taobao.com') > -1 or tab.url.indexOf('www.taobao.com') > -1
						#搜索结果页
						if reLoadTabTimes[tab.id]
							reloadPage -2
						else
							reLoadTabTimes[tab.id] = 1
							chrome.tabs.reload tab.id
					else
						reloadPage -2


#错误检查
requestTimes={}
chrome.webRequest.onErrorOccurred.addListener( (details)->
	#console.log details
	#console.log requestTimes[details.url]
	if !requestTimes[details.url] or requestTimes[details.url] <4
		inject =
			code:"
				(function(){
					var img = new Image();
					img.src = '#{details.url}'
				})();
			"
		if requestTimes[details.url]
			requestTimes[details.url]++
		else
			requestTimes[details.url]=1
		try
			chrome.tabs.executeScript(details.tabId,inject)
		catch e
			e
,{urls: ["http://*.mmstat.com/*"]})



@.cdn = [
	'img*.taobaocdn.com','pics.taobaocdn.com','wwc.taobaocdn.com'
	'g.tbcdn.cn','a.tbcdn.cn','l.tbcdn.cn'
	'img.taobao.com'
	'i.mmcdn.cn'
	'g.searc*.alicdn.com','gi*.md.alicdn.com'
	#aliyuncdn
	'uaction.aliyuncdn.com'
	#各省cdn
	'*.alicdn.com'
	'bj*.alicdn.com'
	'sh*.alicdn.com'
	'gd*.alicdn.com'
	'zj*.alicdn.com'
	'js*.alicdn.com'
	'fj*.alicdn.com'
	'ip.taobao.com'
	#自己
	'127.0.0.1','localhost'
	'visitveb.duapp.com'
	'visitweb.allalla.com'
]


#刷新页面
reloadPage = (page=0)->
	if page
		messenger.postPage page
	gotaobao()
#显示进度
@showPercent = ->
	$.getJSON "#{serverUrlPre}Visit/getpercent",$('form').serialize(),(data)->
		i = 0
		$('[name="keywordName[]"]').each ->
			keyword = this.value
			if keyword and usedCnt=data?[keyword]
				cnt = $('[name="keywordCnt[]"]').get(i++).value
				if cnt > 0
					percent = Math.ceil(usedCnt/cnt*100)
					$(this).closest('td').css('background-size',"#{percent}% 900%").attr('title',"已经完成#{percent}%")
					
				
				

